var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var crypto = require('crypto')

router.post('/', (req, res, next) => {
    // console.log(req.body);
    var sql = 'create table if not exists user(id int not null auto_increment,username varchar(255),password varchar(255),mail varchar(255),primary key (id))';
    db.query(sql, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            var sql = 'SELECT * FROM user WHERE username = ?';
            var sql2 = 'SELECT * FROM user WHERE mail = ?';
            db.query(sql, req.body.username, (err, result) => {
                // console.log('result', result);
                if (err) {
                    throw err;
                    return;
                } else {
                    if (result.length == 0) {
                        db.query(sql2, req.body.mail, (err, info) => {
                            if (err) {
                                throw err;
                                return;
                            } else {
                                if (info.length == 0) {
                                    // console.log('not found');
                                    var md5 = crypto.createHash('md5');
                                    var newPas = md5.update(req.body.password).digest('hex');
                                    var addAql = "INSERT INTO `user` (username,password,mail) VALUES(?, ?, ?)";
                                    var sql_params = [req.body.username, newPas, req.body.mail];
                                    db.query(addAql, sql_params, (err, result) => {
                                        if (err) {
                                            throw err;
                                            return;
                                        } else {
                                            res.send('1');
                                            return;
                                        }
                                    })
                                } else {
                                    res.send('4');
                                }
                            }
                        })
                    } else {
                        res.send('2');
                    }
                }
            })
        }
    })
})

module.exports = router;